<?php
/**
 * Created by PhpStorm.
 * User: surface
 * Date: 2019/1/11
 * Time: 17:55
 */

namespace app\manage\controller;
use app\common\controller\Manage as ManageController;

use Request;

class Stock extends ManageController{

    public function stock()
    {
        if (Request::isAjax()) {
            $stock_model = new \app\common\model\Stock();
            $input = input();
            $name = $input['name'];
            $condition = '';
            if($name) {
                $condition = 'a.name like "%'.$name.'%"';
                //$condition['a.name'] = $name;
            }
            $file = 'stock.*,a.name as goods_name';
            $list = $stock_model
                    ->alias('stock')
                    ->join('goods a', 'a.id = stock.goods_id')
                    ->field($file)
                    ->where($condition)
                    ->paginate($input['limit']);
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = $list->total();
            $re['data'] = $list->items();
            return $re;
        }
        return $this->fetch('index');
    }
    
    public function edit(\think\Request $request) 
    {
        if($request->isAjax()) {
            $respon = new \think\Response();
            $stock_model = new \app\common\model\Stock();
            $data = $request->post();
            if(!is_numeric($data['num'])) {
                return $respon->create(json_encode(['msg' => '库存类型错误']), '', 400);
            }
            $stockInfo = $stock_model->get($data['id']);
            switch($data['type']) {
                case "ck":
                    if($stockInfo->stock < $data['num']) {
                        return $respon->create(json_encode(['msg' => '出库数量大于库存数量']), '', 400);
                    }
                    $stock_model->where('id', $data['id'])->setDec('stock', $data['num']);
                    $type = 1;
                    break;
                case 'rk':
                    $stock_model->where('id', $data['id'])->setInc('stock', $data['num']);
                    $type = 2;
                    break;
                default :
                    return $respon->create(json_encode(['msg' => '类型错误']), '', 400);;
            }
            $insert_data = [
                'goods_id' => $stockInfo->goods_id,
                'ctime' => time(),
                'user_id' => $_SESSION['manage']['manage']['id'],
                'memo' => $data['meno'],
                'type' => $type,
                'quantity' => $data['num']
            ];
            \think\Db::name('stock_list')->insert($insert_data);
            return true;
            //print_r($data);
        } else {
            return $this->display();
        }
    }
}